/**
 * 封装http 请求方法
 */
const appUrl =  'https://tdjhht.hfbright.cn'; // "http://120.53.20.247:8080"  //https://api.tdjhht.com


const reLogin = (api, params, method)=>{
  console.log("重新登录："+api)
  const app = getApp()
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          request('/auth/login', {
            code: res.code
          }, "POST")
            .then(res => {
              app.globalData.session = res.data.session
              if(res.data.status == 1) { // 1 注册过 2 未注册
                wx.setStorageSync('token', res.data.token)
              }else{
                
              }
              request(api, params, method)
                .then(res => {
                  resolve(res)
                })
                .catch(res => {
                  reject(res)
                })
            })
            .catch(res => {
              reject(res)
            })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      fail() {
        console.log("login err")
      }
    })
  })
}

const request = (api,params, method) => {
  const app = getApp()
  console.log(app)
  var token = wx.getStorageSync("token")
  console.log("wx.getStorageSync('token')==============",token)
  //返回promise 对象
  return new Promise((resolve, reject) => {
    var task = wx.request({
      url: appUrl + api,//服务器url+参数中携带的接口具体地址
      data: params || {},//请求参数
      method: method || 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': token  
      },
      success: (res) => {
        console.log("res==============",res)
        //接口访问正常返回数据
        if (res.statusCode == 200) {
          if (res.data.code == 0){ // 0 正确
            resolve(res.data)
            return
          }
          if (res.data.code == 40000) { // 需要鉴权
            reLogin(api, params, method)
            reject(res.data)
            return
          }
          if (res.data.code == 90000) { // 通用错误
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
            console.log(res.data.detail)
            reject(res.data)
            return
          }
          if (res.data.code == 99999) { // 系统错误
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
            console.log(res.data.detail)
            reject(res.data)
            return
          }
          console.log(res.data.code )
          wx.showToast({
            title: '预料之外的code',
            icon: 'none'
          })
          reject(res.data)
        }else if (res.statusCode == 401) {
          if (res.data.code == 40000) { // 需要鉴权
            reLogin(api, params, method)
            reject(res.data)
            return
          }
        }else {
          console.log(res.statusCode)
          //2. 操作不成功返回数据，以toast方式弹出响应信息，如后端未格式化非操作成功异常信息，则可以统一定义异常提示
          console.log('返回状态码非200')
          console.log(res.data)
        }
      },
      fail: function (e) {
        console.log('返回失败')
        reject(e)
      }
    })
    task.onHeadersReceived((header) => {
      // console.log(header) 
      // let cookie = header.header['Set-Cookie'] || header.header['set-cookie'];
      // let token = cookie.match(/token=(.*);/ig);
      
      // if (token && token[0]) {
        
      //   wx.setStorageSync("token", token[0]);
      // }
      // header.cookies.forEach((val) => {
      //   if(val.startsWith('PHPSESSID')) {
      //     wx.setStorageSync("cookie", val);
      //   }
      // });
    });
  })
}

const upLoadFile = (api, name, filePath, params={}) => {
  // const token = wx.getStorageSync("token")
  //返回promise 对象
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: appUrl + api,
      filePath: filePath,
      header: {
        // 'token': token
      },
      name: name,
      formData: params,
      success: function (res) {
        let data = JSON.parse(res.data)
        if(data.code == 0){
          resolve(data)
        }
        if (data.code == 90000) { // 通用错误
          wx.showToast({
            title: data.message,
            icon: 'none'
          })
          console.log(data.detail)
          reject(data)
          return
        }
        if (data.code == 99999) { // 系统错误
          wx.showToast({
            title: data.message,
            icon: 'none'
          })
          console.log(data.detail)
          reject(data)
          return
        }

        wx.showToast({
          title: '预料之外的code',
          icon: 'none'
        })
        reject(data)
      },
      fail: function (e) {
        reject(e)
      }
    });
  })
}
// const requestQiniu = (params) => {
//   const sessionID = wx.getStorageSync("sessionID")
//   //返回promise 对象
//   return new Promise((resolve, reject) => {
//     wx.request({
//       url: qiniuyunApi,//服务器url+参数中携带的接口具体地址
//       data: params || {},//请求参数
//       method: 'POST',
//       header: {
//         'content-type': 'application/x-www-form-urlencoded'
//       },
//       success: function (res) {
//         console.log(res)
//       },
//       fail: function (e) {
//         console.log('返回失败')
//         reject(e)
//       }
//     })
//   })
// }
module.exports = {
  request: request,
  upLoadFile: upLoadFile,
  appUrl: appUrl,
  // qiniuUrl: qiniuUrl
}